//
//  CMTextField.m
//  onecm
//
//  Created by 朱雨 on 2018/5/8.
//  Copyright © 2018年 朱雨. All rights reserved.
//

#import "CMTextField.h"

@implementation CMTextField

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self awakeFromNib];
    }
    return self;
}

- (void)awakeFromNib {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textEditChanged:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self];
    [super awakeFromNib];
}

-(void)textEditChanged:(NSNotification *)obj{
    
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    
    NSString *lang = [[[UIApplication sharedApplication]textInputMode]primaryLanguage];
    
    if ([lang isEqualToString:@"zh-Hans"]) {
        
        UITextRange *selectedRange = [textField markedTextRange];
        
        UITextPosition *positon = [textField positionFromPosition:selectedRange.start offset:0];
        
        if (!positon) {
            
            if (toBeString.length > self.limitTextLeght && self.limitTextLeght >0) {
                
                textField.text = [toBeString substringToIndex:self.limitTextLeght];
            }
        }
        
    }else{
        
        if (toBeString.length > self.limitTextLeght && self.limitTextLeght >0) {
            textField.text = [toBeString substringToIndex:self.limitTextLeght];
        }
    }
    
    if (self.textEdittingBlock) {
        self.textEdittingBlock (textField.text);
    }
    
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:placeholderColor}];
}

@end
